import React, {useState} from "react";
import {Cascader, Form, Input, InputNumber, message, Modal} from "antd";
import {http} from "libs";
import store from "./store";

export default function IForm() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  function handleSubmit() {
    setLoading(true);
    const formData = form.getFieldsValue();
    formData["id"] = store.record.id;
    formData["category_id"] = formData["category_id"].pop()
    http.post("/api/inventory/", formData)
      .then(() => {
        message.success("操作成功");
        store.set("formVisible", false);
        store.fetchRecords()
      })
      .finally(() => setLoading(false))
  }

  //id=1,sn=bh,name=打火机,spec=10,unit=盒,price=20.5
  return (
    <Modal
      open
      maskClosable={false}
      title="编辑商品库存"
      onCancel={store.vSet("formVisible", false)}
      confirmLoading={loading}
      onOk={handleSubmit}>
      <Form autoComplete="off" form={form} initialValues={store.record} labelCol={{span: 6}} wrapperCol={{span: 14}}>
        <Form.Item required name="category_ids" label="商品分类">
          <Cascader allowClear={false}
                    options={store.categories}
                    fieldNames={{label: "name", value: "id"}}
                    placeholder="请输入"/>
        </Form.Item>
        <Form.Item required name="name" label="商品名称">
          <Input placeholder="请输入"/>
        </Form.Item>
        <Form.Item required name="sn" label="商品编号">
          <Input placeholder="请输入"/>
        </Form.Item>
        <Form.Item required name="spec" label="规格">
          <Input placeholder="请输入"/>
        </Form.Item>
        <Form.Item required name="unit" label="基本计量单位">
          <Input placeholder="请输入"/>
        </Form.Item>
        <Form.Item required name="price" label="成本价">
          <InputNumber min={0} style={{width: "100%"}} placeholder="请输入"/>
        </Form.Item>
      </Form>
    </Modal>
  )
}